import type { Request, Response } from 'express';

import { z } from 'zod';

import { RepoModel } from '../../../models/repo';
import Resp from '../../../utils/response';

// 参数校验规则
export const validator = {
  body: z.object({
    remark: z
      .string({
        invalid_type_error: '仓库备注必须是字符串',
        required_error: '仓库备注不能为空',
      })
      .max(500, '描述不能超过500个字符')
      .transform(val => val?.trim()),
  }),
  params: z.object({
    ID: z
      .string({
        invalid_type_error: '仓库ID必须是字符串',
        required_error: '仓库ID不能为空',
      })
      .min(1, '仓库ID不能为空'),
  }),
};

// 更新仓库信息API
export const api = async (req: Request, res: Response): Promise<Response> => {
  try {
    const { ID } = req.params as z.infer<typeof validator.params>;
    const { remark } = req.body as z.infer<typeof validator.body>;

    // 更新仓库信息
    const result = await RepoModel.findByIdAndUpdate(ID, { remark }, { new: true });

    if (!result) {
      return Resp.error(res, 404, '仓库不存在');
    }

    // 返回成功响应
    return Resp.success(res, result, '更新仓库信息成功');
  } catch (error) {
    console.error(error);
    return Resp.catch(res, error);
  }
};
